
require 'dm-appengine/types'
require 'base64'

class ImageFileRecord
  include DataMapper::Resource
  property :id, Serial
  property :data, Blob
  property :original, Integer
  property :original_name, String
  property :width, Integer
  property :height, Integer
  property :resized_to_width, Integer
  property :resized_to_height, Integer
  property :file_name, String

  def data= data
    raise 'Data already set!' if self.data
    
    require 'appengine-apis/images'
    self.image = AppEngine::Images.load(data)
  end

  def to_json
    to_hash.to_json
  end

  def to_hash
    {
      #:data => data,
      :file_name => file_name,
      :id => id
    }
  end

  def self.from_hash h
    i = new
    #i.data = h['data']#Base64.decode64(h['data'])
    i.file_name = h['file_name']
    i
  end

  def self.with_size id, size
    first(:original => id,
      :resized_to_width => size[0],
      :resized_to_height => size[1]
    ) ||
      get(id).resize(size)
  end

  def self.with_size_named name, size
    last(:original_name => name,
      :resized_to_width => size[0],
      :resized_to_height => size[1]
    ) ||
      last(:file_name => name).resize(size)
  end

  def resize size
    self.class.new().tap { |resized|
      resized.image = image.resize(*size)
      resized.original = id
      resized.original_name = file_name
      resized.resized_to_width = size[0]
      resized.resized_to_height = size[1]
      #p 'creating resized image from '+resized.original.to_s
      resized.save
    }
  end

  def image
    require 'appengine-apis/images'
    @image ||= AppEngine::Images.load(data)
  end

  def image= image
    @image = image
    self.width = image.width
    self.height = image.height
    attribute_set(:data, image.data)
  end

end
